package com.tanhua.server.serivce;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务类，封装业务操作，专门给控制器使用
 */
@Service
public class TodayBestService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private RecommendUserApi recommendUserApi;

    /**
     * 接口名称：今日佳人
     */
    public ResponseEntity<Object> queryTodayBest() {
        //1. 获取当前登陆用户
        Long userId = UserHolder.getUserId();

        //2. 根据当前登陆用户，调用Api接口，查询今日佳人
        // db.recommend_user.find({userId:20}).sort({score:-1}).limit(1)
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setRecommendUserId(2L);
            recommendUser.setScore(80D);
        }

        //3. 通过定义的TodayBestVo对象，封装返回的数据
        //3.1 创建返回结果
        TodayBestVo todayBestVo = new TodayBestVo();
        //3.2 根据推荐的用户id查询用户信息（今日佳人）
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
        if (userInfo != null) {
            //3.3 封装用户信息
            BeanUtils.copyProperties(userInfo, todayBestVo);
            //3.4 设置tags
            if (userInfo.getTags() != null) {
                todayBestVo.setTags(userInfo.getTags().split(","));
            }
            //3.4 设置缘分值（调用Api查询的结果）
            todayBestVo.setFateValue(recommendUser.getScore().longValue());
        }
        //4. 把封装好的TodayBestVo设置到响应体中，返回给前端
        return ResponseEntity.ok(todayBestVo);
    }

    /**
     * 接口名称：推荐朋友 (首页推荐)
     */
    public ResponseEntity<Object> queryRecommendation(RecommendQueryVo vo) {
        //1. 获取当前登陆用户
        Long userId = UserHolder.getUserId();

        //2. 根据当前登陆用户，调用Api接口，分页查询推荐用户
        PageResult pageResult =
                recommendUserApi.queryRecommendation(userId, vo.getPage(), vo.getPagesize());
        //3. 获取查询到的数据
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
        if (recommendUserList == null || recommendUserList.size() == 0) {
            // 如果查询为空，推荐用户默认就是id=5-10
            recommendUserList = new ArrayList<>();
            for (Integer i = 5; i < 10; i++) {
                RecommendUser ru = new RecommendUser();
                ru.setRecommendUserId(i.longValue());
                ru.setScore(70D + i);
                recommendUserList.add(ru);
            }
        }
        //4. 封装TodayBestVo集合对象
        //4.1 创建集合
        List<TodayBestVo> result = new ArrayList<>();
        //4.2 转换：把查询到的recommendUserList数据，封装到todayBestVo
        for (RecommendUser recommendUser : recommendUserList) {
            TodayBestVo todayBestVo = new TodayBestVo();
            UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
            if (userInfo != null) {
                //封装用户信息
                BeanUtils.copyProperties(userInfo, todayBestVo);
                //设置tags
                if (userInfo.getTags() != null) {
                    todayBestVo.setTags(userInfo.getTags().split(","));
                }
                //设置缘分值（调用Api查询的结果）
                todayBestVo.setFateValue(recommendUser.getScore().longValue());

                //把封装好的vo对象，添加到集合
                result.add(todayBestVo);
            }
        }

        //4.3 把封装好的vo设置到pageResult中
        pageResult.setItems(result);

        //4. 把封装好的TodayBestVo设置到响应体中，返回给前端
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 接口名称：佳人信息 （首页点击某一个推荐用户，查看明细）
     */
    public ResponseEntity<Object> queryPersonalInfo(Long recommendUserId) {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();

        //2. 查询推荐佳人用户
        UserInfo userInfo = userInfoApi.findById(recommendUserId);

        //3. 创建返回的对象
        TodayBestVo vo = new TodayBestVo();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }

        //4. 查询某一个用户（20）的缘分值
        //db.recommend_user.find({userId:20,recommendUserId:4})
        Long score = recommendUserApi.queryScore(userId, recommendUserId);
        vo.setFateValue(score);
        return ResponseEntity.ok(vo);
    }

    @Autowired(required = false)
    private QuestionApi questionApi;

    /**
     * 接口名称：查询陌生人问题
     */
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        // 根据用户id查询tb_question表
        Question question = questionApi.findByUserId(userId);
        // 获取陌生人问题，如果为空给一个默认值
        String txt = question != null ? question.getTxt() : "我们做一个朋友~";
        return ResponseEntity.ok(txt);
    }

    @Reference
    private UserLocationApi userLocationApi;

    /**
     * 接口名称：搜附近
     */
    public ResponseEntity<Object> searchNear(String gender, Long distance) {
        //1. 获取用户id
        Long userId = UserHolder.getUserId();

        //2. 调用api查询附近人
        // 为什么不能返回UserLocation：因为其中的GeoJsonPoint对象没有实现序列化接口
        // 所以，需要定义UserLocationVo并返回此对象
        List<UserLocationVo> locationList = userLocationApi.searchNear(userId, distance);

        //3. 返回结果
        List<NearUserVo> voList = new ArrayList<>();

        //4. 封装voList返回结果
        if (locationList != null && locationList.size() > 0) {
            for (UserLocationVo userLocationVo : locationList) {
                // 搜附近：不能包含自己
                if (userLocationVo.getUserId() == userId) {
                    continue;
                }

                // 搜附件： 根据gender筛选
                UserInfo userInfo = userInfoApi.findById(userLocationVo.getUserId());
                if (userInfo != null) {
                    if (!gender.equals(userInfo.getGender())) {
                        continue;
                    }

                    // 满足条件，返回
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getId());
                    nearUserVo.setAvatar(userInfo.getAvatar());
                    nearUserVo.setNickname(userInfo.getNickname());
                    voList.add(nearUserVo);
                }
            }
        }

        return ResponseEntity.ok(voList);
    }

    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;

    /**
     * 喜欢
     * @param likeUserId
     * @return
     */
    public Boolean likeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        String id = userLikeApi.saveUserLike(userId, likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        if (userLikeApi.isMutualLike(userId, likeUserId)) {
            friendApi.save(userId,likeUserId);
        }
        return true;
    }

    /**
     * 不喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean disLikeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        return userLikeApi.deleteUserLike(userId, likeUserId);
    }


    /**
     * 探花
     * @return
     */
    public ResponseEntity<Object> queryCardsList() {

        Long userId = UserHolder.getUserId();

        List<UserInfo> userInfoList = userInfoApi.queryRandom10(userId);

        List<TodayBestVo> voList = new ArrayList<>();
        if (userInfoList != null && userInfoList.size()>0){
            for (UserInfo userInfo : userInfoList) {
                TodayBestVo todayBestVo = new TodayBestVo();
                todayBestVo.setId(userInfo.getId());
                todayBestVo.setAvatar(userInfo.getAvatar());
                todayBestVo.setNickname(userInfo.getNickname());
                todayBestVo.setGender(userInfo.getGender());
                todayBestVo.setAge(userInfo.getAge());
                todayBestVo.setTags(userInfo.getTags().split(","));

                voList.add(todayBestVo);
            }
        }
        return ResponseEntity.ok(voList);
    }
}
